// 开源安全创意工坊 - 前端JavaScript功能

// 全局变量
let currentProjectId = null;
let draggedTask = null;

// 初始化函数
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

function initializeApp() {
    // 初始化工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // 初始化弹出框
    const popoverTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="popover"]'));
    popoverTriggerList.map(function (popoverTriggerEl) {
        return new bootstrap.Popover(popoverTriggerEl);
    });

    // 初始化任务拖拽
    initializeTaskDragAndDrop();
    
    // 初始化其他功能
    initializeTeamMembers();
    initializeSearch();
    initializeNotifications();
}

// 任务看板拖拽功能
function initializeTaskDragAndDrop() {
    const taskCards = document.querySelectorAll('.task-card');
    const taskColumns = document.querySelectorAll('.task-column');

    // 为每个任务卡片添加拖拽事件
    taskCards.forEach(card => {
        card.addEventListener('dragstart', handleDragStart);
        card.addEventListener('dragend', handleDragEnd);
    });

    // 为每个列添加拖拽事件
    taskColumns.forEach(column => {
        column.addEventListener('dragover', handleDragOver);
        column.addEventListener('drop', handleDrop);
        column.addEventListener('dragenter', handleDragEnter);
        column.addEventListener('dragleave', handleDragLeave);
    });
}

function handleDragStart(e) {
    draggedTask = this;
    this.classList.add('dragging');
    e.dataTransfer.effectAllowed = 'move';
    e.dataTransfer.setData('text/html', this.outerHTML);
}

function handleDragEnd(e) {
    this.classList.remove('dragging');
    
    // 清除所有拖拽样式
    document.querySelectorAll('.drag-over').forEach(el => {
        el.classList.remove('drag-over');
    });
}

function handleDragOver(e) {
    if (e.preventDefault) {
        e.preventDefault();
    }
    e.dataTransfer.dropEffect = 'move';
    return false;
}

function handleDragEnter(e) {
    this.classList.add('drag-over');
}

function handleDragLeave(e) {
    if (e.target.classList.contains('task-column')) {
        this.classList.remove('drag-over');
    }
}

function handleDrop(e) {
    if (e.stopPropagation) {
        e.stopPropagation();
    }
    
    const column = this;
    const newStatus = column.getAttribute('data-status');
    const taskId = draggedTask.getAttribute('data-task-id');
    
    // 更新任务状态
    updateTaskStatus(taskId, newStatus);
    
    // 移动任务卡片
    column.querySelector('.task-list').appendChild(draggedTask);
    
    // 更新任务计数
    updateTaskCounts();
    
    return false;
}

// 更新任务状态（发送到后端）
function updateTaskStatus(taskId, newStatus) {
    fetch(`/api/tasks/${taskId}/status`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({ status: newStatus })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification('任务状态更新成功', 'success');
        } else {
            showNotification('任务状态更新失败', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('网络错误，请重试', 'error');
    });
}

// 更新任务计数
function updateTaskCounts() {
    const columns = document.querySelectorAll('.task-column');
    columns.forEach(column => {
        const count = column.querySelectorAll('.task-card').length;
        const countElement = column.querySelector('.task-count');
        if (countElement) {
            countElement.textContent = count;
        }
    });
}

// 添加新任务
function addTask(columnId) {
    const taskTitle = prompt('请输入任务标题：');
    if (!taskTitle) return;
    
    const taskDescription = prompt('请输入任务描述（可选）：') || '';
    
    const taskData = {
        title: taskTitle,
        description: taskDescription,
        status: columnId,
        project_id: currentProjectId
    };
    
    fetch('/api/tasks', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(taskData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 创建新任务卡片
            const taskCard = createTaskCard(data.task);
            const column = document.querySelector(`[data-status="${columnId}"] .task-list`);
            column.appendChild(taskCard);
            
            updateTaskCounts();
            showNotification('任务添加成功', 'success');
        } else {
            showNotification('任务添加失败', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('网络错误，请重试', 'error');
    });
}

// 创建任务卡片
function createTaskCard(task) {
    const card = document.createElement('div');
    card.className = 'task-card';
    card.draggable = true;
    card.setAttribute('data-task-id', task.id);
    
    card.innerHTML = `
        <h6>${task.title}</h6>
        <p class="small text-muted mb-2">${task.description}</p>
        <div class="task-actions">
            <button class="btn btn-sm btn-outline-primary" onclick="editTask(${task.id})">
                <i class="fas fa-edit"></i>
            </button>
            <button class="btn btn-sm btn-outline-danger" onclick="deleteTask(${task.id})">
                <i class="fas fa-trash"></i>
            </button>
        </div>
    `;
    
    // 添加拖拽事件
    card.addEventListener('dragstart', handleDragStart);
    card.addEventListener('dragend', handleDragEnd);
    
    return card;
}

// 编辑任务
function editTask(taskId) {
    const taskCard = document.querySelector(`[data-task-id="${taskId}"]`);
    const currentTitle = taskCard.querySelector('h6').textContent;
    const currentDescription = taskCard.querySelector('p').textContent;
    
    const newTitle = prompt('编辑任务标题：', currentTitle);
    if (!newTitle) return;
    
    const newDescription = prompt('编辑任务描述：', currentDescription) || '';
    
    const taskData = {
        title: newTitle,
        description: newDescription
    };
    
    fetch(`/api/tasks/${taskId}`, {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(taskData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新任务卡片
            taskCard.querySelector('h6').textContent = newTitle;
            taskCard.querySelector('p').textContent = newDescription;
            
            showNotification('任务更新成功', 'success');
        } else {
            showNotification('任务更新失败', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('网络错误，请重试', 'error');
    });
}

// 删除任务
function deleteTask(taskId) {
    if (!confirm('确定要删除这个任务吗？')) return;
    
    fetch(`/api/tasks/${taskId}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 移除任务卡片
            const taskCard = document.querySelector(`[data-task-id="${taskId}"]`);
            taskCard.remove();
            
            updateTaskCounts();
            showNotification('任务删除成功', 'success');
        } else {
            showNotification('任务删除失败', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('网络错误，请重试', 'error');
    });
}

// 团队成员管理
function initializeTeamMembers() {
    const teamMembersContainer = document.getElementById('team-members');
    if (!teamMembersContainer) return;
    
    const addMemberBtn = document.getElementById('add-member-btn');
    if (addMemberBtn) {
        addMemberBtn.addEventListener('click', addTeamMember);
    }
}

function addTeamMember() {
    const memberName = prompt('请输入团队成员姓名：');
    if (!memberName) return;
    
    const memberRole = prompt('请输入成员角色（可选）：') || '开发者';
    
    const memberHtml = `
        <div class="team-member mb-2">
            <div class="input-group">
                <input type="text" class="form-control" name="team_members[]" value="${memberName}" readonly>
                <input type="text" class="form-control" name="team_roles[]" value="${memberRole}" placeholder="角色">
                <button class="btn btn-outline-danger" type="button" onclick="removeTeamMember(this)">
                    <i class="fas fa-trash"></i>
                </button>
            </div>
        </div>
    `;
    
    const container = document.getElementById('team-members');
    container.insertAdjacentHTML('beforeend', memberHtml);
}

function removeTeamMember(button) {
    if (confirm('确定要移除这个团队成员吗？')) {
        button.closest('.team-member').remove();
    }
}

// 搜索功能
function initializeSearch() {
    const searchInput = document.getElementById('search-input');
    if (!searchInput) return;
    
    searchInput.addEventListener('input', debounce(handleSearch, 300));
}

function handleSearch(e) {
    const query = e.target.value.toLowerCase();
    const projectCards = document.querySelectorAll('.project-card');
    
    projectCards.forEach(card => {
        const title = card.querySelector('.card-title').textContent.toLowerCase();
        const description = card.querySelector('.card-text').textContent.toLowerCase();
        
        if (title.includes(query) || description.includes(query)) {
            card.style.display = 'block';
            card.classList.add('fade-in-up');
        } else {
            card.style.display = 'none';
        }
    });
}

// 防抖函数
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 通知系统
function initializeNotifications() {
    // 检查浏览器是否支持通知
    if ('Notification' in window) {
        // 请求通知权限
        if (Notification.permission === 'default') {
            Notification.requestPermission();
        }
    }
}

function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `alert alert-${type} alert-dismissible fade show position-fixed`;
    notification.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    
    notification.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    document.body.appendChild(notification);
    
    // 3秒后自动移除
    setTimeout(() => {
        if (notification.parentNode) {
            notification.parentNode.removeChild(notification);
        }
    }, 3000);
    
    // 浏览器通知
    if ('Notification' in window && Notification.permission === 'granted') {
        new Notification('开源安全创意工坊', {
            body: message,
            icon: '/static/favicon.ico'
        });
    }
}

// 点赞功能
function likeTip(tipId) {
    fetch(`/api/tips/${tipId}/like`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // 更新点赞数
            const likesElement = document.getElementById(`likes-${tipId}`);
            if (likesElement) {
                likesElement.textContent = data.likes;
            }
            
            // 添加动画效果
            const likeButton = event.target.closest('button');
            likeButton.classList.add('animate__animated', 'animate__pulse');
            
            showNotification('点赞成功！', 'success');
        } else {
            showNotification('点赞失败，请重试', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('网络错误，请重试', 'error');
    });
}

// 收藏功能
function favoriteTip(tipId) {
    fetch(`/api/tips/${tipId}/favorite`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showNotification(data.message, 'success');
            
            // 更新收藏按钮状态
            const favoriteBtn = event.target.closest('button');
            if (data.favorited) {
                favoriteBtn.classList.remove('btn-outline-warning');
                favoriteBtn.classList.add('btn-warning');
            } else {
                favoriteBtn.classList.remove('btn-warning');
                favoriteBtn.classList.add('btn-outline-warning');
            }
        } else {
            showNotification('操作失败，请重试', 'error');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showNotification('网络错误，请重试', 'error');
    });
}

// 项目统计
function updateProjectStats() {
    const stats = {
        total: document.querySelectorAll('.project-card').length,
        completed: document.querySelectorAll('.badge.bg-success').length,
        inProgress: document.querySelectorAll('.badge.bg-warning').length,
        planning: document.querySelectorAll('.badge.bg-info').length
    };
    
    // 更新统计卡片
    Object.keys(stats).forEach(key => {
        const element = document.getElementById(`stats-${key}`);
        if (element) {
            element.textContent = stats[key];
        }
    });
}

// 导出项目数据
function exportProjectData(projectId) {
    fetch(`/api/projects/${projectId}/export`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 创建下载链接
                const blob = new Blob([JSON.stringify(data.project, null, 2)], {
                    type: 'application/json'
                });
                const url = URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = `project_${data.project.name}_${new Date().toISOString().split('T')[0]}.json`;
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                URL.revokeObjectURL(url);
                
                showNotification('项目数据导出成功', 'success');
            } else {
                showNotification('导出失败，请重试', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('网络错误，请重试', 'error');
        });
}

// 分享项目
function shareProject(projectId) {
    const projectUrl = `${window.location.origin}/projects/${projectId}`;
    
    if (navigator.share) {
        navigator.share({
            title: '开源安全创意工坊 - 项目分享',
            url: projectUrl
        }).then(() => {
            showNotification('分享成功', 'success');
        }).catch(() => {
            // 用户取消分享，不做处理
        });
    } else {
        // 复制到剪贴板
        navigator.clipboard.writeText(projectUrl).then(() => {
            showNotification('项目链接已复制到剪贴板', 'success');
        }).catch(() => {
            showNotification('复制失败，请手动复制', 'error');
        });
    }
}

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    // Ctrl/Cmd + K 打开搜索
    if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
        e.preventDefault();
        const searchInput = document.getElementById('search-input');
        if (searchInput) {
            searchInput.focus();
        }
    }
    
    // Ctrl/Cmd + N 新建项目
    if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
        e.preventDefault();
        window.location.href = '/create-project';
    }
    
    // Esc 关闭模态框
    if (e.key === 'Escape') {
        const openModal = document.querySelector('.modal.show');
        if (openModal) {
            const modal = bootstrap.Modal.getInstance(openModal);
            modal.hide();
        }
    }
});

// 页面可见性变化处理
document.addEventListener('visibilitychange', function() {
    if (document.visibilityState === 'visible') {
        // 页面重新可见时刷新数据
        refreshProjectData();
    }
});

// 刷新项目数据
function refreshProjectData() {
    if (currentProjectId) {
        fetch(`/api/projects/${currentProjectId}/tasks`)
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // 更新任务看板
                    updateTaskBoard(data.tasks);
                }
            })
            .catch(error => {
                console.error('Error refreshing data:', error);
            });
    }
}

// 更新任务看板
function updateTaskBoard(tasks) {
    // 清空所有任务列
    document.querySelectorAll('.task-list').forEach(list => {
        list.innerHTML = '';
    });
    
    // 重新添加任务
    tasks.forEach(task => {
        const taskCard = createTaskCard(task);
        const column = document.querySelector(`[data-status="${task.status}"] .task-list`);
        if (column) {
            column.appendChild(taskCard);
        }
    });
    
    updateTaskCounts();
}

// 工具函数：格式化日期
function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'short',
        day: 'numeric'
    });
}

// 工具函数：格式化时间
function formatTime(dateString) {
    const date = new Date(dateString);
    return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
    });
}

// 工具函数：生成随机颜色
function getRandomColor() {
    const colors = ['primary', 'secondary', 'success', 'danger', 'warning', 'info'];
    return colors[Math.floor(Math.random() * colors.length)];
}

// 工具函数：防抖
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 工具函数：节流
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    }
}

// 导出函数供全局使用
window.addTeamMember = addTeamMember;
window.removeTeamMember = removeTeamMember;
window.addTask = addTask;
window.editTask = editTask;
window.deleteTask = deleteTask;
window.likeTip = likeTip;
window.favoriteTip = favoriteTip;
window.exportProjectData = exportProjectData;
window.shareProject = shareProject;
